package com.bulletelc.apollopre.utils;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

/**
 * author: lhl
 * time  : 2017/10/20
 * desc  : 网络工具类
 */

public final class NetworkUtil {

    private NetworkUtil() {
        //empty
    }

    /**
     * 打开网络设置界面
     */
    public static void openWirelessSettings(Context context) {
        context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }

    /**
     * 获取活动网络信息
     * @param context
     * @return
     */
    public static NetworkInfo getNetWorkInfo(Context context){
        return ((ConnectivityManager)(context.getSystemService(Context.CONNECTIVITY_SERVICE))).getActiveNetworkInfo();
    }

    /**
     * 判断网络是否连接
     * 需添加权限  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     * @param context 上下文
     * @return
     */
    public static boolean isConnected(Context context){
        NetworkInfo info = getNetWorkInfo(context);
        return info != null && info.isConnected();
    }


    /**
     * 判断当前网络状态是否Mobile
     * @param context
     * @return
     */
    public static boolean isMobile(Context context) {
        NetworkInfo info=getNetWorkInfo(context);
        return info != null && info.getType() == ConnectivityManager.TYPE_MOBILE;
    }

    /**
     * 判断WiFi是否连接
     * @return
     */
    public static boolean isWifiConnected(Context context){
        NetworkInfo info=getNetWorkInfo(context);
        return info != null && info.getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 判断WiFi是否打开
     */
    public static boolean isWifiEnabled(Context context){
        WifiManager wifiManager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wifiManager.isWifiEnabled();
    }

    /**
     * 打开/关闭WiFi
     * @param enabled true:打开,false:关闭
     */
    public static void setWifiEnabled(Context context,boolean enabled){
        WifiManager wifiManager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (enabled) {
            if (!wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(true);
            }
        } else {
            if (wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(false);
            }
        }
    }

    /**
     * 判断网络是否是4G
     * @param context
     * @return
     */
    public static boolean is4G(Context context) {
        NetworkInfo info = getNetWorkInfo(context);
        return info != null && info.isAvailable() && info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE;
    }
}
